<template>
  <w-modal
    ref="WModal"
    title="文字识别(本地图片)"
    width="1100px"
    :ok-text="identifyArr.length > 0 ? '清除' : '识别'"
    :ok-type="identifyArr.length > 0 ? 'danger' : 'primary'"
    @ok="okClick"
  >
    <a-row :gutter="16">
      <a-col span="6">
        <image-up ref="WImageUp" />
      </a-col>
      <a-col span="18">
        <div v-if="identifyArr.length">
          <p v-for="(v, k) in identifyArr" :key="k">
            {{ v.words }}
          </p>
        </div>
      </a-col>
    </a-row>
  </w-modal>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Api } from '@/config/api'
import WModal, { ModalComType } from '@/components/global/modal'
import ImageUp, { ServerImageUpType } from '@/components/global/imageUp/server'

@Component({
  name: 'WebToolImageIdentifyTextLoacl',
  components: {
    ImageUp,
    WModal
  }
})
export default class WebToolImageIdentifyTextLoacl extends Vue {
  // 识别出的文字
  identifyArr = []

  // 图片识别按钮点击
  imageInentify () {
    if (this.identifyArr.length) {
      this.identifyArr = [];
      (this.$refs.WImageUp as ServerImageUpType).clear()
      return
    }
    (this.$refs.WModal as ModalComType).showLoading();
    (this.$refs.WImageUp as any).upImage()
      .then((data: any) => {
        this.$wAxios
          .$post(Api.baidu.localTextIdentify, {
            localPath: data.filepath
          })
          .then((data) => {
            if (data.words_result && data.words_result.length > 0) {
              this.identifyArr = data.words_result
            } else {
              this.$message.error('没有识别出文字')
            }
          })
          .catch(() => {
            this.identifyArr = []
          })
          .finally(() => {
            (this.$refs.WModal as ModalComType).hideLoading()
          })
      })
      .catch((err: any) => {
        (this.$refs.WModal as ModalComType).hideLoading()
        this.$message.error(err.msg)
      })
  }

  /**
   * 显示弹窗
   */
  show () {
    (this.$refs.WModal as ModalComType).show()
  }

  /**
   * 清除按钮点击
   */
  clearData () {
    this.identifyArr = [];
    (this.$refs.WImageUp as any).clear()
  }

  okClick() {
    if (this.identifyArr.length) {
      this.clearData()
    } else {
      this.imageInentify()
    }
  }
}
</script>

<style scoped></style>
